<template>
	<view class="warp">
		<!-- 自定义状态栏 -->
		<custom-status-bar gradient-type="assistant"></custom-status-bar>
		
		<!-- AI助手标题 -->
		<view class="header">
			<text class="header-title">智能咨询AI助手</text>
		</view>
		
		<!-- 横栏选项 -->
		<view class="tab-container">
			<view 
				class="tab-item" 
				:class="{ active: activeTab === 'books' }"
				@click="switchTab('books')"
			>
				<text class="tab-text">智能购书资讯</text>
			</view>
			<view 
				class="tab-item" 
				:class="{ active: activeTab === 'study' }"
				@click="switchTab('study')"
			>
				<text class="tab-text">智能学习资料</text>
			</view>
		</view>
		
		<!-- 聊天记录区域 -->
		<scroll-view 
			class="chat-container" 
			scroll-y="true" 
			:scroll-top="scrollTop"
			ref="scrollView"
		>
			<view class="message-list">
				<view 
					v-for="(message, index) in messages" 
					:key="index"
					:class="['message-item', message.role === 'user' ? 'user-message' : 'ai-message']"
				>
					<view class="message-content">
						<text class="message-text">{{ message.content }}</text>
					</view>
					<view class="message-time">
						<text class="time-text">{{ message.time }}</text>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- 输入区域 -->
		<view class="input-container">
			<input 
				class="message-input" 
				v-model="inputMessage" 
				placeholder="请输入消息..." 
				@confirm="sendMessage"
			/>
			<button class="send-button" @click="sendMessage">发送</button>
		</view>
	</view>
</template>

<script>
	// #ifdef APP
	import customStatusBar from "@/components/custom-status-bar/custom-status-bar.vue";
	// #endif
	
	export default {
		// #ifdef APP
		components: {
			customStatusBar
		},
		// #endif
		data() {
			return {
				activeTab: 'books', // 默认选中智能购书资讯
				inputMessage: '',
				messages: [
					{
						role: 'ai',
						content: '您好！我是您的AI助手，请问有什么可以帮助您的吗？',
						time: this.getCurrentTime()
					}
				],
				scrollTop: 0
			}
		},
		onShow() {
			// 保留登录状态判断的基本功能
			this.hasLogin = uniCloud.getCurrentUserInfo().tokenExpired > Date.now()
		},
		methods: {
			// 将函数移到methods内部，符合Vue 3选项式API规范
			async getQwenResponse(message, activeTab) {
				const API_KEY = 'sk-39e524c7930242b8b7dce61b0615e1d3';
				const MODEL = 'qwen-plus';
				
				// 构建提示词，根据不同的tab提供不同的上下文
				let systemPrompt = '';
				if (activeTab === 'books') {
					systemPrompt = '你是一个智能购书资讯助手，请根据用户的问题推荐合适的书籍。';
				} else if (activeTab === 'study') {
					systemPrompt = '你是一个智能学习资料助手，请根据用户的问题提供学习建议和资料推荐。';
				}
				
				try {
					const response = await uni.request({
						url: 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
						method: 'POST',
						header: {
							'Authorization': `Bearer ${API_KEY}`,
							'Content-Type': 'application/json',
							'X-DashScope-SSE': 'enable'
						},
						data: {
							model: MODEL,
							messages: [
								{
									role: 'system',
									content: systemPrompt
								},
								{
									role: 'user',
									content: message
								}
							],
							parameters: {
								max_tokens: 1500,
								temperature: 0.8,
								top_p: 0.8
							}
						}
					});
					console.log(response.statusCode);
					console.log('Response data:', response.data);
					// 修复数据访问路径，根据实际返回结构获取内容
					if (response.statusCode === 200 && response.data && response.data.choices && response.data.choices.length > 0) {
						return response.data.choices[0].message.content || '抱歉，我没有理解您的问题，请重新描述。';
					} else {
						console.error('API Error:', response);
						if (response.statusCode !== 200) {
							return '服务暂时不可用，请稍后再试。';
						} else {
							return '服务返回数据格式异常，请稍后再试。';
						}
					}
				} catch (error) {
					console.error('Network Error:', error);
					return '网络连接异常，请检查网络设置。';
				}
			},
			
			switchTab(tab) {
				this.activeTab = tab;
				// 清空输入框
				this.inputMessage = '';
				
				// 添加提示消息
				const tabNames = {
					books: '智能购书资讯',
					study: '智能学习资料'
				};
				
				this.messages.push({
					role: 'ai',
					content: `已切换到${tabNames[tab]}模式，请输入相关问题。`,
					time: this.getCurrentTime()
				});
				
				// 滚动到底部
				this.$nextTick(() => {
					this.scrollTop += 1000;
				});
			},
			
			// 修改: 更新sendMessage方法以使用真实的AI接口
			async sendMessage() {
				if (!this.inputMessage.trim()) return;
				
				// 添加用户消息
				const userMessage = {
					role: 'user',
					content: this.inputMessage,
					time: this.getCurrentTime()
				};
				
				this.messages.push(userMessage);
				
				// 清空输入框
				const userInput = this.inputMessage;
				this.inputMessage = '';
				
				// 滚动到底部
				this.$nextTick(() => {
					this.scrollTop += 1000;
				});
				
				// 显示AI正在输入的提示
				const typingMessage = {
					role: 'ai',
					content: '正在思考中...',
					time: this.getCurrentTime()
				};
				this.messages.push(typingMessage);
				
				this.$nextTick(() => {
					this.scrollTop += 1000;
				});
				
				// 调用通义千问API
				try {
					const aiResponse = await this.getQwenResponse(userInput, this.activeTab);
					
					// 更新AI回复
					this.messages[this.messages.length - 1] = {
						role: 'ai',
						content: aiResponse,
						time: this.getCurrentTime()
					};
				} catch (error) {
					// 错误处理
					this.messages[this.messages.length - 1] = {
						role: 'ai',
						content: '抱歉，回复生成失败，请稍后重试。',
						time: this.getCurrentTime()
					};
				}
				
				// 滚动到底部
				this.$nextTick(() => {
					this.scrollTop += 1000;
				});
			},
			
			getCurrentTime() {
				const now = new Date();
				return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
			}
		}
	}
</script>

<style>
	/* #ifndef APP-NVUE */
	page {
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		min-height: 100%;
		height: auto;
	}
	view {
		font-size: 14px;
		line-height: inherit;
	}
	/* #endif */
	
	.warp {
		display: flex;
		flex-direction: column;
		height: 100vh;
		/* 添加渐变背景色 */
		background: linear-gradient(135deg, #CFDEF3 0%, #E0EAFC 100%);
		min-height: 100vh;
	}
	
	/* AI助手标题 */
	.header {
		height: 88rpx;
		background: linear-gradient(135deg, #74ebd5 0%, #ACB6E5 100%);
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 30rpx;
	}
	
	.header-title {
		color: #FFFFFF;
		font-size: 36rpx;
		font-weight: bold;
	}
	
	/* 横栏选项 */
	.tab-container {
		display: flex;
		flex-direction: row;
		background-color: #FFFFFF;
		border-bottom: 1px solid #e0e0e0;
	}
	
	.tab-item {
		flex: 1;
		padding: 20rpx;
		text-align: center;
		border-bottom: 4rpx solid transparent;
	}
	
	.tab-item.active {
		border-bottom-color: #007AFF;
	}
	
	.tab-text {
		color: #333333;
		font-size: 28rpx;
	}
	
	/* 聊天区域 */
	.chat-container {
		flex: 1;
		padding: 20rpx;
		/* 修改: 确保聊天区域可以正确滚动 */
		flex-shrink: 1;
		overflow-y: auto;
	}
	
	.message-list {
		display: flex;
		flex-direction: column;
		/* 修改: 确保内容可以正确展开 */
		min-height: 100%;
	}
	
	.message-item {
		display: flex;
		flex-direction: column;
		margin-bottom: 20rpx;
		max-width: 80%;
	}
	
	.user-message {
		margin-left: 130rpx;
		width: 700rpx;
	}
	
	.ai-message {
		align-self: flex-start;
	}
	
	.message-content {
		padding: 20rpx;
		border-radius: 10rpx;
	}
	
	.user-message .message-content {
		background-color: #007AFF;
	}
	
	.ai-message .message-content {
		background-color: #FFFFFF;
		border: 1px solid #e0e0e0;
	}

	/* 修改: 完善消息样式，解决用户消息超出屏幕问题 */
	.message-text {
		color: #333333;
		font-size: 28rpx;
		word-wrap: break-word; /* 允许长单词换行 */
		word-break: break-all; /* 强制换行 */
	}

	.user-message .message-text {
		color: #FFFFFF;
		word-wrap: break-word; /* 允许长单词换行 */
		word-break: break-all; /* 强制换行 */
	}

	.message-time {
		align-self: flex-end;
		margin-top: 10rpx;
	}
	
	.time-text {
		color: #999999;
		font-size: 20rpx;
	}
	
	/* 输入区域 */
	.input-container {
		display: flex;
		flex-direction: row;
		padding: 20rpx;
		background-color: #FFFFFF;
		border-top: 1px solid #e0e0e0;
		/* 修改: 固定在底部 */
		flex-shrink: 0;
	}
	
	.message-input {
		flex: 1;
		padding: 15rpx;
		border: 1px solid #e0e0e0;
		border-radius: 10rpx;
		font-size: 28rpx;
	}
	
	.send-button {
		margin-left: 20rpx;
		padding: 15rpx 30rpx;
		background-color: #007AFF;
		color: #FFFFFF;
		border-radius: 10rpx;
		font-size: 28rpx;
	}
	
	/* 原有样式保持不变 */
	.section-box{
		display: flex;
		flex-direction: row;
		align-items: center;
		padding: 20rpx;
	}
	.decoration{
		width: 4px;
		height: 12px;
		border-radius: 10px;
		background-color: #2979ff;
	}
	.section-text{
		color: #333;
		margin-left: 15rpx;
	}

	/* #ifdef APP-NVUE */
	.warp {
		background-color: #fff;
	}
	/* #endif */

	.example-body {
		flex-direction: column;
		padding: 15px;
		background-color: #ffffff;
	}

	.image {
		width: 50rpx;
		height: 50rpx;
	}
	
	.big-number{
		font-size: 50rpx;
		font-weight: 700;
		font-stretch: condensed;
		font-style:oblique;
	}
	
	.text {
		text-align: center;
		font-size: 26rpx;
		margin-top: 10rpx;
	}

	.example-body {
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
	}

	.grid-item-box {
		flex: 1;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 15px 0;
	}

	.banner-image {
		width: 100%;
		height: 400rpx;
	}

	.swiper-box {
		height: 400rpx;
	}

	.search-icons {
		padding: 16rpx;
	}

	.search-container-bar {
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		justify-content: center;
		align-items: center;
		position: fixed;
		left: 0;
		right: 0;
		z-index: 10;
		background-color: #fff;
	}

	/* #ifndef APP-NVUE || VUE3*/
	::v-deep
	/* #endif */
	.uni-searchbar__box {
		border-width: 0;
	}

	/* #ifndef APP-NVUE || VUE3 */
	::v-deep
	/* #endif */
	.uni-input-placeholder {
		font-size: 28rpx;
	}
</style>